package com.baocai.tools_redis.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author ：minyang
 * @date ：Created in 2019/7/23 18:58
 * 分布式锁
 */
@Component
public class DistributedLock {

    private static final Logger logger = LoggerFactory.getLogger(DistributedLock.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate redisTemplate;

    private static String LOCK_PREFIX = "prefix_";

    private static final int expire_second = 30;//过期时间（秒）


    public boolean lock(String key, String value) {

        boolean result = false;
        key = LOCK_PREFIX + key;

        if (redisTemplate.opsForValue().setIfAbsent(key, value)) {
            redisTemplate.opsForValue().set(key, value, 3600);
            return true;
        }
        return result;
    }

    public void unlock(String key, String value) {
        try {
            key = LOCK_PREFIX + key;
            String currentValue = (String) redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
